package com.dms.modules.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dms.common.exception.BusinessException;
import com.dms.common.security.SecurityUtils;
import com.dms.modules.merchant.entity.Merchant;
import com.dms.modules.merchant.service.MerchantService;
import com.dms.modules.product.entity.Product;
import com.dms.modules.product.service.ProductService;
import com.dms.modules.user.entity.UserFavorite;
import com.dms.modules.user.mapper.UserFavoriteMapper;
import com.dms.modules.user.service.UserFavoriteService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户收藏服务实现类
 */
@Slf4j
@Service
public class UserFavoriteServiceImpl extends ServiceImpl<UserFavoriteMapper, UserFavorite> implements UserFavoriteService {

    @Autowired
    @Lazy
    private ProductService productService;
    
    @Autowired
    private MerchantService merchantService;

    @Autowired
    private UserFavoriteMapper userFavoriteMapper;

    @Override
    public List<UserFavorite> getByUserId(Integer type, Integer limit) {
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {
            throw new BusinessException("用户未登录");
        }
        
        LambdaQueryWrapper<UserFavorite> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserFavorite::getUserId, userId)
                .eq(type != null, UserFavorite::getType, type)
                .eq(UserFavorite::getDeleted, 0)
                .orderByDesc(UserFavorite::getCreateTime)
                .last(limit != null ? "LIMIT " + limit : "");
        return list(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addFavorite(Integer type, Long targetId) {
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {
            throw new BusinessException("用户未登录");
        }
        
        // 检查是否已收藏
        if (isFavorite(type, targetId)) {
            return true;
        }

        UserFavorite favorite = new UserFavorite();
        favorite.setUserId(userId);
        favorite.setType(type);
        favorite.setTargetId(targetId);
        favorite.setCreateTime(LocalDateTime.now());
        favorite.setUpdateTime(LocalDateTime.now());
        favorite.setDeleted(0);

        return save(favorite);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeFavorite(Integer type, Long targetId) {
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {
            throw new BusinessException("用户未登录");
        }

        LambdaUpdateWrapper<UserFavorite> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(UserFavorite::getUserId, userId)
               .eq(UserFavorite::getType, type)
               .eq(UserFavorite::getTargetId, targetId)
               .eq(UserFavorite::getDeleted, 0)
               .set(UserFavorite::getDeleted, 1)
               .set(UserFavorite::getUpdateTime, LocalDateTime.now());

        return update(wrapper);
    }

    @Override
    public boolean isFavorite(Integer type, Long targetId) {
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {
            return false;
        }
        
        LambdaQueryWrapper<UserFavorite> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserFavorite::getUserId, userId)
                .eq(UserFavorite::getType, type)
                .eq(UserFavorite::getTargetId, targetId)
                .eq(UserFavorite::getDeleted, 0);
        return count(wrapper) > 0;
    }

    @Override
    public IPage<Product> getFavoriteProducts(Integer pageNum, Integer pageSize) {
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {
            throw new BusinessException("用户未登录");
        }
        
        Page<Product> page = new Page<>(pageNum, pageSize);
        return baseMapper.selectFavoriteProducts(page, userId);
    }

    @Override
    public IPage<Merchant> getFavoriteMerchants(Integer pageNum, Integer pageSize) {
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {
            throw new BusinessException("用户未登录");
        }
        
        Page<Merchant> page = new Page<>(pageNum, pageSize);
        return userFavoriteMapper.selectFavoriteMerchants(page, userId);
    }

    @Override
    public long getFavoriteCount(Long targetId, Integer type) {
        LambdaQueryWrapper<UserFavorite> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserFavorite::getTargetId, targetId)
                .eq(UserFavorite::getType, type)
                .eq(UserFavorite::getDeleted, 0);
        return count(wrapper);
    }
} 